package com.doctracker.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 模板管理服务
 * 负责保存和加载改名模板
 */
public class TemplateManager {
    
    private static final String DATA_DIR = System.getProperty("user.home") + File.separator + ".doctracker";
    private static final String TEMPLATES_DIR = DATA_DIR + File.separator + "templates";
    private static final String TEMPLATES_HISTORY_FILE = TEMPLATES_DIR + File.separator + "history.json";
    
    private ObjectMapper objectMapper;
    
    /**
     * 模板项
     */
    public static class TemplateItem {
        private String name;
        private String templateString;
        private LocalDateTime saveTime;
        private String fileName;
        private int elementCount;
        
        public TemplateItem() {}
        
        public TemplateItem(String name, String templateString, LocalDateTime saveTime, String fileName, int elementCount) {
            this.name = name;
            this.templateString = templateString;
            this.saveTime = saveTime;
            this.fileName = fileName;
            this.elementCount = elementCount;
        }
        
        // Getter和Setter
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getTemplateString() { return templateString; }
        public void setTemplateString(String templateString) { this.templateString = templateString; }
        public LocalDateTime getSaveTime() { return saveTime; }
        public void setSaveTime(LocalDateTime saveTime) { this.saveTime = saveTime; }
        public String getFileName() { return fileName; }
        public void setFileName(String fileName) { this.fileName = fileName; }
        public int getElementCount() { return elementCount; }
        public void setElementCount(int elementCount) { this.elementCount = elementCount; }
        
        @Override
        public String toString() {
            return name + " (" + elementCount + "个元素)";
        }
    }
    
    public TemplateManager() {
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule());
        createDirectories();
    }
    
    /**
     * 创建必要的目录
     */
    private void createDirectories() {
        try {
            File templatesDir = new File(TEMPLATES_DIR);
            if (!templatesDir.exists()) {
                templatesDir.mkdirs();
                System.out.println("创建模板目录: " + templatesDir.getAbsolutePath());
            }
        } catch (Exception e) {
            System.err.println("创建模板目录失败: " + e.getMessage());
        }
    }
    
    /**
     * 保存模板
     * 
     * @param templateName 模板名称
     * @param ruleElements 规则元素列表
     * @return 是否保存成功
     */
    public boolean saveTemplate(String templateName, List<FileRenameService.RuleElement> ruleElements) {
        try {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = sanitizeFileName(templateName) + "_" + timestamp + ".json";
            String filePath = TEMPLATES_DIR + File.separator + fileName;
            
            // 转换为模板字符串
            String templateString = convertToTemplateString(ruleElements);
            
            // 创建保存的数据结构
            Map<String, Object> data = new HashMap<>();
            data.put("name", templateName);
            data.put("templateString", templateString);
            data.put("ruleElements", ruleElements);
            data.put("saveTime", LocalDateTime.now());
            data.put("elementCount", ruleElements.size());
            
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(filePath), data);
            addToHistory(templateName, fileName, templateString, ruleElements.size());
            System.out.println("模板保存成功: " + filePath);
            return true;
        } catch (IOException e) {
            System.err.println("保存模板失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 加载模板
     * 
     * @param fileName 文件名
     * @return 规则元素列表
     */
    public List<FileRenameService.RuleElement> loadTemplate(String fileName) {
        try {
            String filePath = TEMPLATES_DIR + File.separator + fileName;
            File file = new File(filePath);
            
            if (!file.exists()) {
                System.err.println("模板文件不存在: " + filePath);
                return new ArrayList<>();
            }
            
            @SuppressWarnings("unchecked")
            Map<String, Object> data = objectMapper.readValue(file, Map.class);
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> elementsData = (List<Map<String, Object>>) data.get("ruleElements");
            
            List<FileRenameService.RuleElement> ruleElements = new ArrayList<>();
            if (elementsData != null) {
                for (Map<String, Object> elementData : elementsData) {
                    String type = (String) elementData.get("type");
                    String value = (String) elementData.get("value");
                    ruleElements.add(new FileRenameService.RuleElement(type, value));
                }
            }
            
            System.out.println("模板加载成功: " + fileName + " (包含 " + ruleElements.size() + " 个元素)");
            return ruleElements;
        } catch (IOException e) {
            System.err.println("加载模板失败: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取模板历史列表
     * 
     * @return 模板历史列表
     */
    public List<TemplateItem> getTemplateHistory() {
        try {
            File historyFile = new File(TEMPLATES_HISTORY_FILE);
            if (!historyFile.exists()) {
                rebuildHistoryFromFiles();
                if (!historyFile.exists()) {
                    return new ArrayList<>();
                }
            }
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> historyData = objectMapper.readValue(historyFile, List.class);
            
            List<TemplateItem> templates = new ArrayList<>();
            for (Map<String, Object> itemData : historyData) {
                TemplateItem item = new TemplateItem();
                item.setName((String) itemData.get("name"));
                item.setTemplateString((String) itemData.get("templateString"));
                item.setFileName((String) itemData.get("fileName"));
                item.setElementCount((Integer) itemData.get("elementCount"));
                
                // 处理时间字段
                Object saveTimeObj = itemData.get("saveTime");
                if (saveTimeObj instanceof List) {
                    @SuppressWarnings("unchecked")
                    List<Integer> timeArray = (List<Integer>) saveTimeObj;
                    if (timeArray.size() >= 6) {
                        item.setSaveTime(LocalDateTime.of(
                            timeArray.get(0), timeArray.get(1), timeArray.get(2),
                            timeArray.get(3), timeArray.get(4), timeArray.get(5)
                        ));
                    }
                } else if (saveTimeObj instanceof String) {
                    item.setSaveTime(LocalDateTime.parse((String) saveTimeObj));
                }
                
                templates.add(item);
            }
            
            // 按保存时间倒序排列
            templates.sort((a, b) -> {
                if (a.getSaveTime() == null && b.getSaveTime() == null) return 0;
                if (a.getSaveTime() == null) return 1;
                if (b.getSaveTime() == null) return -1;
                return b.getSaveTime().compareTo(a.getSaveTime());
            });
            
            return templates;
        } catch (IOException e) {
            System.err.println("读取模板历史失败: " + e.getMessage());
            rebuildHistoryFromFiles();
            return new ArrayList<>();
        }
    }
    
    /**
     * 添加到历史记录
     */
    private void addToHistory(String templateName, String fileName, String templateString, int elementCount) {
        try {
            List<TemplateItem> history = getTemplateHistory();
            
            TemplateItem newItem = new TemplateItem(templateName, templateString, LocalDateTime.now(), fileName, elementCount);
            history.add(0, newItem); // 添加到开头
            
            // 限制历史记录数量
            if (history.size() > 50) {
                history = history.subList(0, 50);
            }
            
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(TEMPLATES_HISTORY_FILE), history);
        } catch (IOException e) {
            System.err.println("更新模板历史失败: " + e.getMessage());
        }
    }
    
    /**
     * 从文件重建历史记录
     */
    private void rebuildHistoryFromFiles() {
        try {
            File templatesDir = new File(TEMPLATES_DIR);
            if (!templatesDir.exists()) {
                return;
            }
            
            List<TemplateItem> history = new ArrayList<>();
            File[] files = templatesDir.listFiles((dir, name) -> name.endsWith(".json") && !name.equals("history.json"));
            
            if (files != null) {
                for (File file : files) {
                    try {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> data = objectMapper.readValue(file, Map.class);
                        
                        TemplateItem item = new TemplateItem();
                        item.setName((String) data.get("name"));
                        item.setTemplateString((String) data.get("templateString"));
                        item.setFileName(file.getName());
                        
                        Object elementCount = data.get("elementCount");
                        if (elementCount instanceof Integer) {
                            item.setElementCount((Integer) elementCount);
                        } else {
                            item.setElementCount(0);
                        }
                        
                        // 处理时间
                        Object saveTimeObj = data.get("saveTime");
                        if (saveTimeObj instanceof List) {
                            @SuppressWarnings("unchecked")
                            List<Integer> timeArray = (List<Integer>) saveTimeObj;
                            if (timeArray.size() >= 6) {
                                item.setSaveTime(LocalDateTime.of(
                                    timeArray.get(0), timeArray.get(1), timeArray.get(2),
                                    timeArray.get(3), timeArray.get(4), timeArray.get(5)
                                ));
                            }
                        } else if (saveTimeObj instanceof String) {
                            item.setSaveTime(LocalDateTime.parse((String) saveTimeObj));
                        } else {
                            item.setSaveTime(LocalDateTime.now());
                        }
                        
                        history.add(item);
                    } catch (Exception e) {
                        System.err.println("解析模板文件失败: " + file.getName() + ", " + e.getMessage());
                    }
                }
                
                // 按时间排序
                history.sort((a, b) -> {
                    if (a.getSaveTime() == null && b.getSaveTime() == null) return 0;
                    if (a.getSaveTime() == null) return 1;
                    if (b.getSaveTime() == null) return -1;
                    return b.getSaveTime().compareTo(a.getSaveTime());
                });
                
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(TEMPLATES_HISTORY_FILE), history);
                System.out.println("模板历史重建完成，共找到 " + history.size() + " 个模板");
            }
        } catch (IOException e) {
            System.err.println("重建模板历史失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除模板
     * 
     * @param fileName 文件名
     * @return 是否删除成功
     */
    public boolean deleteTemplate(String fileName) {
        try {
            File file = new File(TEMPLATES_DIR + File.separator + fileName);
            boolean deleted = file.delete();
            if (deleted) {
                // 重建历史记录
                rebuildHistoryFromFiles();
                System.out.println("模板删除成功: " + fileName);
            }
            return deleted;
        } catch (Exception e) {
            System.err.println("删除模板失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 转换规则元素为模板字符串
     */
    private String convertToTemplateString(List<FileRenameService.RuleElement> ruleElements) {
        StringBuilder template = new StringBuilder();
        for (FileRenameService.RuleElement element : ruleElements) {
            if ("field".equals(element.getType())) {
                template.append("{").append(element.getValue()).append("}");
            } else {
                template.append(element.getValue());
            }
        }
        return template.toString();
    }
    
    /**
     * 清理文件名中的无效字符
     */
    private String sanitizeFileName(String fileName) {
        return fileName.replaceAll("[\\\\/:*?\"<>|]", "_").trim();
    }
} 